/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.shiro.ShiroKit;
import cn.emove.core.shiro.ShiroUser;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.model.OpencardDto;
import cn.emove.modular.system.model.RechargeDto;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.OpencardService;
import cn.emove.modular.system.service.RechargeService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.OpencardWrapper;
import cn.emove.modular.system.warpper.RechargeWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统管理员控制器
 *
 */
@Controller
@RequestMapping("/recharge")
public class RechargeController extends BaseController {

    private static String PREFIX = "/modular/system/recharge/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private RechargeService rechargeService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    /**
     * 跳转到查看开卡列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "recharge.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String rechargeOrderNo,
                       @RequestParam(required = false) String shopName,
                       @RequestParam(required = false) String shopAdr,
                       @RequestParam(required = false) String createTime,
                       @RequestParam(required = false) String rechargeStatus) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        Page<Map<String, Object>> maps = rechargeService.selectRecharges(null, rechargeOrderNo, shopName, beginTime, endTime,shopAdr,rechargeStatus);
        Page wrapped = new RechargeWrapper(maps).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }

    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/userData")
    @ResponseBody
    public JSONObject selectUser(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        //查询工单用户
        userList = userService.selectWorkUser();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("userId")), c.get("name"));
        }
        return ServerJson;
    }

    /**
     * 跳转到添加充值
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String rechargeAdd() {
        return PREFIX + "recharge_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectShopData();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("shopId")), c.get("shopName"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(RechargeDto rechargeDto) {
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        rechargeDto.setOperatorId(userId);
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/rechargeSave";
        String param = JSON.toJSONString(rechargeDto);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            String message = String.valueOf(json.get("message"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                if("用户没有开卡".equals(message)){
                    throw new ServiceException(BizExceptionEnum.SERVER_NOCARD_ERROR);
                }
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }

    /**
     * 跳转至详情页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/recharge_detail")
    public String rechargeDetail(@RequestParam int id,String statusName,Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("id", id);
        model.addAttribute("statusName", statusName);
        LogObjectHolder.me().set(id);
        return PREFIX + "recharge_detail.html";
    }

    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/rechargeDetailData/{id}")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object ticketDetailData(@PathVariable int id) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/rechargeDetail?rechargeId="+id;
        String result = HttpUtil.sendGet(url);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return json;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }
    }
}
